 class MenuTree {
    constructor() {
    }
    init(data) {
        let menus = []

        data.forEach(item => {
            Object.assign(item, { children: [] })
            if (item.parent_id == 0) {
                menus.push(item)
            }
        })
        return menus
    }
    getMenus(data) {
        let menus = this.init(data)
        function _getTree(data, menus) {
            menus.forEach(menu => {
                data.forEach(item => {
                    if (menu._id == item.parent_id) {
                        menu.children.push(item)
                    }
                })
                if (menu.children.length > 0) {
                    _getTree(data, menu.children)
                } else {
                    delete menu['children']
                }
            })
            return menus
        }
        let res = _getTree(data, menus)
        return JSON.stringify(res)
    }
    getDom(data, name='title') {
        let menus = []
        function _getDom(data, level = 1) {
            data.forEach(menu => {
                menus.push({value: menu._id, label: `|${'-'.repeat(level)}${menu[name]}`})
                if (menu.children && menu.children.length > 0) {
                    _getDom(menu.children, level + 1)                    
                }
            })
            return menus
        }
        return _getDom(data)
    }
}
module.exports = new MenuTree()